﻿using System;
using System.Collections.Generic;
using System.Text;
using MediaPortal.GUI.Library;

// based on VideoSort

namespace MediaPortal.Plugins.Trailers
{
   public class GUIListItemTrailerComparer : IComparer<GUIListItem>
  {
    public enum SortMethod
    {
      Title = 0,
      ReleaseDate = 1,
      Year = 2,
    }
    
    private SortMethod _sortMethod;
    private bool _sortAsc;

    public GUIListItemTrailerComparer(SortMethod sortMethod, bool ascending)
    {
      _sortMethod = sortMethod;
      _sortAsc = ascending;
    }

    public int Compare(GUIListItem item1, GUIListItem item2)
    {
      if (item1 == item2) return 0;
      if (item1 == null) return -1;
      if (item2 == null) return -1;
      if (item1.IsFolder && item1.Label == "..") return -1;
      if (item2.IsFolder && item2.Label == "..") return -1;
      if (item1.IsFolder && !item2.IsFolder) return -1;
      else if (!item1.IsFolder && item2.IsFolder) return 1;

      Trailer t1;
      Trailer t2;

      switch (_sortMethod)
      {
        case SortMethod.Year:
          {
            try
            {
              t1 = (Trailer)item1.AlbumInfoTag;
              t2 = (Trailer)item2.AlbumInfoTag;
            }
            catch {
              return 0;
            }
            if (_sortAsc)
            {
              if (t1.Year > t2.Year) return 1;
              if (t1.Year < t2.Year) return -1;
            }
            else
            {
              if (t1.Year > t2.Year) return -1;
              if (t2.Year < t1.Year) return 1;
            }

            return 0;
          }

        case SortMethod.Title:

          if (_sortAsc)
          {
            return String.Compare(item1.Label, item2.Label, true);
          }
          else
          {
            return String.Compare(item2.Label, item1.Label, true);
          }

        case SortMethod.ReleaseDate:
          try
          {
            t1 = (Trailer)item1.AlbumInfoTag;
            t2 = (Trailer)item2.AlbumInfoTag;
          }
          catch
          {
            return 0;
          }

          if (t1.ReleaseDate == null) return -1;
          if (t2.ReleaseDate == null) return -1;
 
          if (_sortAsc)
          {
            return DateTime.Compare(t1.ReleaseDate.Date, t2.ReleaseDate.Date);
          }
          else
          {
            return DateTime.Compare(t2.ReleaseDate.Date, t1.ReleaseDate.Date);
          }
      }
      return 0;
    }

  }
}

